package org.example.doubleFinger;

import org.example.link_list.ListNode;

public class Delete_the_nth_to_last_node_of_the_linked_list {
    public static void main(String[] args) {
        //删除链表的倒数第 N 个结点

        //给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点
        ListNode listNode2 = new ListNode(5);
        listNode2.next = null;
        ListNode listNode3 = new ListNode(4,listNode2);
        ListNode listNode4 = new ListNode(3,listNode3);
        ListNode listNode5 = new ListNode(2,listNode4);
        ListNode head = new ListNode(1,listNode5);
        head.next=null;
        ListNode node = removeNthFromEnd1(head, 1);
        while(node!=null){
            System.out.println(node.val);
            node = node.next;
        }
    }
    public static ListNode removeNthFromEnd1(ListNode head, int n) {
        ListNode vir = new ListNode();
        vir.next = head;
        ListNode slow  = vir;
        ListNode fast = vir;
        ListNode temp = null;
        while(fast!=null){
            if (n>0){
                fast = fast.next;
                n--;
            }else {
                temp = slow;
                slow = slow.next;
                fast = fast.next;
            }
        }
        temp.next = slow.next;
        slow.next =null;
        return vir.next;
    }
}
